package com.dagit.network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.dagit.network.traffic.IMessage;
import com.dagit.network.traffic.Message;

class ListenerThread implements Runnable{
	private Socket socket;
	public ListenerThread(Socket s){
		this.socket = s;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		boolean _try = true;
		while(_try){
			ObjectInputStream in = null;
			ObjectOutputStream out = null;
			try {
				in = new ObjectInputStream(socket.getInputStream());
				out = new ObjectOutputStream(socket.getOutputStream());
				while(in.available() < 0){
					
				}
				Message<Object> message= (Message<Object>)in.readObject();
				IMessage<Object, Object> process = (IMessage<Object, Object>)Class.forName(message.getClazz()).newInstance(); //TODO class for name is slow try object pool
				Object ret  = process.processMessage(message.getInput());
				out.writeObject(ret);
				out.flush();
				_try = false;
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (InstantiationException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}finally{
				if(in != null){
					try {
						in.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(out != null){
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (socket != null){
					try {
						socket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}	
			
		}
	}
	
}

public class LocalServerSocket implements Runnable{
	private static Lock lock = new ReentrantLock();
	private int port;
	public LocalServerSocket(int port) throws IOException{
		this.port = port;
	}
	
	@Override
	public void run() {
		
		try {
			ServerSocket socket = new ServerSocket(port);
			lock.lock();
			while(true){
				Socket s = socket.accept();
				ListenerThread thread = new ListenerThread(s);
				new Thread(thread).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			lock.unlock();
		}		
	}
	
	public static void start(int port) throws IOException{
		LocalServerSocket ss = new LocalServerSocket(port);
		new Thread(ss).start();

	}
	
	public static void main(String[] args) throws Exception {
		LocalServerSocket.start(8090);
	}
	
}
